package com.share.config.filter.log;

import com.share.common.utils.ParamUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.*;

/**
 * 处理 json
 * 参考  https://blog.csdn.net/jiaobuchong/article/details/104665382
 */
public class LogReadRequestWrapper extends HttpServletRequestWrapper {
    //body提数据和xml
    private byte[] body;

    private final int SIZE = 1024;

    private Map<String, String[]> bodyMap = new HashMap<>();

    public LogReadRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);

        //读取数据
        String reqContentType = request.getContentType();
        this.body = readBody(request.getInputStream());
        if (reqContentType.contains("form")) {
            addToMap(request.getQueryString());
            addToMap(body == null ? null : new String(body));
        }
    }

    // 把kv参数 转换未map存储起来
    private void addToMap(String str) {
        if (StringUtils.isNotBlank(str)) {
            Map<String, String[]> map = ParamUtil.kvs2map(str);
            bodyMap.putAll(map);
            Set<String> keys = map.keySet();
            for (String key : keys) {
                String[] tmpValue = map.get(key);
                String value = ArrayUtils.isNotEmpty(tmpValue) ? tmpValue[0] : "";
                super.setAttribute(key, value);
            }
        }
    }

    // 这个是核心方法---会被调用  userPageReq
    @Override
    public String getParameter(String name) {
        String[] parameterValues = getParameterValues(name);
        return (parameterValues != null && parameterValues.length > 0) ? parameterValues[0] : null;
    }

    // 会被调用
    @Override
    public Map<String, String[]> getParameterMap() {
        return this.bodyMap;
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return new Vector<>(getParameterMap().keySet()).elements();
    }


    //会被调用
    @Override
    public String[] getParameterValues(String name) {
        return getParameterMap().get(name);
    }

    //提供一个提取的接口
    public byte[] getBody() {
        return body;
    }

    //读取body的内容
    private byte[] readBody(InputStream is) {
        //读取body里面的数据---核心逻辑
        BufferedInputStream bis = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream(SIZE);
        try {
            bis = new BufferedInputStream(is);
            byte[] buffer = new byte[SIZE];
            int len = -1;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bos.toByteArray();
    }

    @Override
    public ServletInputStream getInputStream() {
        //通用代码
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.body);
        return new ServletInputStream() {
            @Override
            public int read() {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }
        };
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
}
